<?php
function unlinkRecursive($dir, $deleteRootToo) {
    if (!$dh = @opendir($dir)) {
        return;
    }
    while (false !== ($obj = readdir($dh))) {
        if ($obj == '.' || $obj == '..') {
            continue;
        }

        if (!@unlink($dir . '/' . $obj)) {
            unlinkRecursive($dir . '/' . $obj, true);
        }
    }

    closedir($dh);

    if ($deleteRootToo) {
        @rmdir($dir);
    }

    return;
}

function ExtractFile($sql, $title) {
    require("../library/MySQL.dll.php");
    $db = new MySQL();
    $result = $db->select($sql);

    //set $Use_Titel = 1 to generate title, 0 not to use title
    $useTitle = 1;

    $count = $db->numrows($result);
    for ($i = 0; $i < count($title); $i++) {
        $header .= $title[$i] . "\t";
    }
    while ($row = $db->fetch($result)) {
        $line = '';
        $i = 0;
        foreach ($row as $value) {
            if ((!isset($result)) OR ($value == "")) {
                $value = "\t";
            } else {
                $value = str_replace('"', '""', $value);
                $value = '"' . $value . '"' . "\t";
            }
            $line .= $value;
            $i ++;
        }

        $data .= trim($line) . "\n";
    }
    $data = str_replace("\r", "", $data);
    if ($data == "") {
        $data = "\n(0) Records Found!\n";
    }

    $tmp = "$header\n$data";

    $tmp = chr(255) . chr(254) . mb_convert_encoding($tmp, 'UTF-16LE', 'UTF-8');

    print $tmp;
}